package com.rs.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author zhouwz

 * ApplicationContext上下文应用类
 * @date 2020/3/27 14:23
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    /**
     * 声明一个静态变量保存
     */
    private static ApplicationContext applicationContext;

    /**
     * 初始化上下文
     *
     * @param applicationContext 上下文
     * @throws BeansException 异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取自动注入Bean对象
     *
     * @param clazz Bean的类名
     * @param <T>   Bean实例对象
     * @return Bean实例对象
     */
    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext != null) {
            return applicationContext.getBean(clazz);
        } else {
            return null;
        }
    }

    /**
     * 获取上下文对象
     *
     * @return 上下文对象
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
